package com.xinyan.zookeeper;

import com.alibaba.druid.pool.DruidDataSource;
import com.xinyan.druid.MysqlDruid;
import com.xinyan.dto.DruidDto;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import sun.jvm.hotspot.debugger.sparc.SPARCThreadContext;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;

/**
 * @author xinyan.xie
 * @description zookeeper连接配置信息
 * @date 2020/5/15
 */
public class ZkConfig {
    //1.初始化zookeeper连接配置

    public static String PATH = "MYSQL_CONFIG";
    private static CountDownLatch watch = new CountDownLatch(1);
    public static String URL = "jdbc:mysql://127.0.0.1:3306/LG-study";
    public static  String DRIVER_CLASS = "com.mysql.jdbc.Driver";
    public static String USER_NAME = "root";
    public static String PASSWORD = "passwd";
    public static void main(String[] args) throws Exception {
        CuratorFramework build = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .namespace(PATH) //独立的命名空间，实现业务隔离
                .connectionTimeoutMs(500)
                .sessionTimeoutMs(500)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        build.start();
        System.out.println("zookeeper连接已成功创建=============================");


            String username = build.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/USER_NAME", USER_NAME.getBytes());
        String password = build.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/PASSWORD", PASSWORD.getBytes());
        String url = build.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/URL", URL.getBytes());
        String driverClassName = build.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/DRIVER_CLASS", DRIVER_CLASS.getBytes());
        DruidDto druidDto = new DruidDto();
        druidDto.setDriverClass(DRIVER_CLASS);
        druidDto.setPassword(PASSWORD);
        druidDto.setUrl(URL);
        druidDto.setUsername(USER_NAME);
        Connection connection = MysqlDruid.getConnection(druidDto);
        System.out.println("当前数据库连接为："+connection);

        build.close();
        System.out.println("zookeeper连接关闭=================");






    }

    //2.初始化读取配置信息，将默认数据读取并存到节点中--config.yml


    //3.数据库连接成功，打印第一个数据库中默认表到数据，操作jpa

    //4。注册监听器，监听PATH节点下数据是否变化

    //5。若节点数据变化，则断开数据库连接，重新初始化连接数据==config-1.yml

    //6.重新建立连接，打印第一个数据库中默认表到数据，操作jpa



}
